package com.woniu40.petai_user.service;

import com.woniu40.petai_user.entity.Comment;
import com.woniu40.petai_user.entity.Report;
import com.woniu40.petai_user.mapper.CommentMapper;
import com.woniu40.petai_user.mapper.ReportMapper;
import com.woniu40.petai_user.vo.CommentVo;
import com.woniu40.petai_user.vo.ReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentService {

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    ReportMapper reportMapper;

    public int addComment(Comment comment){
        int insert = commentMapper.insert(comment);
        return insert;
    }


    private List<CommentVo> tempComment = new ArrayList<>();

    public List<CommentVo> listCommentVo(Integer dynamicId){
        // 查询父节点
        List<CommentVo> commentVos = commentMapper.findParentIdNull(dynamicId);
        for (CommentVo commentVo : commentVos){
            Integer commentId = commentVo.getCommentId();
            String parentUsername0 = commentVo.getUserName();
            List<CommentVo> childrenComments = commentMapper.findParentIdNotNull(commentId);
            // 查询子评论
            combineChildren(childrenComments,parentUsername0);
            commentVo.setReplayCommentVoList(tempComment);
            tempComment = new ArrayList<>();
        }
        return commentVos;
    }

    private void combineChildren(List<CommentVo> childrenComments,String parentUsername0){
        if (childrenComments.size()>0){
            for (CommentVo childComment : childrenComments){
                //子评论的用户名
                String parentUsername = childComment.getUserName();
                //

                childComment.setParentUsername(parentUsername0);
                tempComment.add(childComment);
                Integer childId = childComment.getCommentId();
                recusively(childId,parentUsername);}


        }

    }

    private void recusively(Integer childId, String parentUsername0) {
        List<CommentVo> replyComments = commentMapper.findByReplayId(childId);
        if (replyComments.size()>0){
            for (CommentVo replyComment : replyComments){
                String parentUsername = replyComment.getUserName();
                replyComment.setParentUsername(parentUsername0);
                Integer replyId = replyComment.getCommentId();
                tempComment.add(replyComment);
                recusively(replyId,parentUsername);
            }
        }
    }

    public int saveComment(CommentVo commentVo){
        commentVo.setCreateTime(new Date());
        return commentMapper.insert0(commentVo);
    }

    public int insertCommentReport(ReportVo reportVo){
        reportVo.setCreateTime(new Date());
        return reportMapper.insert(reportVo);
    }

}
